vim9script noclear

const NUM = 8
var strlist = repeat([''], NUM)
var sts = repeat([0], NUM)
var cword = ''

export def MarkSearch(force: bool): void
	(force) ? search(cword, 'sW') : search(cword, 'sbW')
enddef

export def MarkSet(): void
	var str = expand("<cword>")
	var num_idx = sts->index(0)
	var str_idx = strlist->index(str)

	if str_idx > -1
		sts[str_idx] = 0
		strlist[str_idx] = ''
	elseif num_idx > -1
		sts[num_idx] = 1
		strlist[num_idx] = str
		cword = str
	else
		return
	endif

	MarkUpdate()
enddef

export def MarkClear(): void
	for i in range(NUM)
		sts[i] = 0
		strlist[i] = ''
	endfor

	cword = ''
	MarkUpdate()
enddef

export def MarkUpdate(): void
	windo MarkShow()
enddef

export def MarkShow(): void
	if empty(&ft)
		return
	endif

	if !exists("w:STRList")
		w:STRList = repeat([''], NUM)
	endif

	if !exists("w:IDs")
		w:IDs = repeat([0], NUM)
	endif

	for i in range(NUM)
		if sts[i] == 0
			if w:IDs[i] != 0
				matchdelete(w:IDs[i])
				w:IDs[i] = 0
				w:STRList[i] = ''
			endif
		else
			if w:IDs[i] == 0
				w:STRList[i] = strlist[i]
				w:IDs[i] = matchadd($"MarkWord{i}", $'\<{w:STRList[i]}\>', 10, -1)
			elseif w:STRList[i] != strlist[i]
				matchdelete(w:IDs[i])
				w:STRList[i] = strlist[i]
				w:IDs[i] = matchadd($"MarkWord{i}", $'\<{w:STRList[i]}\>', 10, -1)
			endif
		endif
	endfor
enddef
